<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input
        v-model="params.name"
        clearable
        placeholder="请输入内容"
        class="search-main"
      />
      <el-button @click="doSearch" type="primary">查询</el-button>
    </div>
    <!-- 添加企业 -->
    <div class="create-container">
      <el-button
        v-auth-btn="'park:enterprise:add_edit'"
        @click="$router.push('/park/enterprise/add')"
        type="primary"
        >添加企业</el-button
      >
      <!-- 高阶组件的权限控制 -->
      <!-- <auth-button btn-string="park:enterprise:add_edit">
        <el-button type="primary" @click="$router.push('/park/enterprise/add')"
          >添加企业</el-button
        >
      </auth-button> -->
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list" @expand-change="expandChange">
        <!-- 展开合同 -->
        <el-table-column type="expand">
          <template #default>
            <el-table :data="rentList">
              <el-table-column
                label="租赁楼宇"
                width="320"
                prop="buildingName"
              />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status">
                <!-- 作用域插槽 + 插值表达式来 渲染标签,对象中括号取值法 -->
                <template slot-scope="scope">
                  <el-tag>{{ mapStatus[scope.row.status] }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button
                    :disabled="scope.row.status === 3"
                    @click="outRent(scope.row.id)"
                    size="mini"
                    type="text"
                    >退租</el-button
                  >
                  <el-button
                    :disabled="scope.row.status !== 3"
                    @click="delRent(scope.row.id)"
                    size="mini"
                    type="text"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>

        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button @click="addRent(scope.row)" size="mini" type="text"
              >添加合同</el-button
            >
            <el-button
              v-auth-btn="'park:enterprise:query'"
              @click="viewRent(scope.row.id)"
              size="mini"
              type="text"
              >查看</el-button
            >
            <el-button
              v-auth-btn="'park:enterprise:add_edit'"
              @click="editRent(scope.row.id)"
              size="mini"
              type="text"
              >编辑</el-button
            >
            <el-button
              v-auth-btn="'park:enterprise:remove'"
              @click="delExterprise(scope.row.id)"
              size="mini"
              type="text"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 底部分页 -->
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        :current-page="params.page"
        :page-size="params.pageSize"
        @current-change="pageChange"
      />
    </div>

    <!-- 添加合同对话框 -->
    <el-dialog
      title="添加合同"
      :visible="rentDialogVisible"
      width="580px"
      @close="closeDialog"
    >
      <!-- 表单模版 -->
      <div class="form-container">
        <el-form
          ref="addForm"
          :model="rentForm"
          :rules="rentRules"
          label-position="top"
        >
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in buildList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>

          <el-form-item label="租赁合同" prop="contractId">
            <el-upload action="#" :http-request="uploadFile">
              <el-button size="small" type="primary" plain
                >上传合同文件</el-button
              >
              <div slot="tip" class="el-upload__tip">
                支持扩展名：.doc .docx .pdf, 文件大小不超过5M
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>

        <el-button @click="submitRentForm" size="mini" type="primary"
          >确 定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getEnterpriseListAPI,
  getRentListAPI,
  getRentBuildListAPI,
  uploadAPI,
  createRentAPI,
  delExterpriseAPI,
  outRentAPI,
  delRentAPI,
} from "@/api/enterprise";

export default {
  name: "Building",
  data() {
    return {
      total: 0, // 总条数
      params: {
        page: 1, // 当前页码
        pageSize: 10, // 每页显示的条数
        name: "", // 查询字段name
      },
      list: [], // 企业列表
      rentList: [], // 企业租赁信息列表
      buildList: [], //存储楼宇列表数据
      mapStatus: {
        0: "待生效",
        1: "生效中",
        2: "已到期",
        3: "已退租",
      },
      currentRow: null, // 当前展开的企业行数据
      rentDialogVisible: false, //控制合同新增对话框显示和隐藏
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: "", // 合同Url
        enterpriseId: null, // 企业id
        type: 0, // 合同类型
        rentTime: [], // 合同时间
      },
      rentRules: {
        buildingId: [
          { required: true, message: "请选择楼宇", trigger: "change" },
        ],
        rentTime: [
          { required: true, message: "请选择租赁日期", trigger: "change" },
        ],
        contractId: [
          { required: true, message: "请上传合同文件", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if (!this.rentForm.contractUrl) {
                callback(new Error("请上传合法合同文件"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    // 获取企业列表
    async getList() {
      let res = await getEnterpriseListAPI(this.params);
      this.list = res.data.rows;
      this.total = res.data.total;
    },
    async expandChange(row, expandedRows) {
      this.currentRow = row; // 更新当前行数据
      // 经过研究：row表示当前点击的那一行的数据，expandedRows：表示当前所有展开行数据
      console.log(row, expandedRows);
      // 优化：根据研究：发现row对象中的id如果在expandedRows中存在，则表示展开，就应该发送请求
      // 否则就是收起，不应该发请求
      // findIndex如果没有找到返回的是-1
      let index = expandedRows.findIndex((item) => item.id === row.id);
      if (index > -1) {
        // 1. 获取企业id
        // 2. 根据企业id获取租赁信息
        let res = await getRentListAPI(row.id);
        // console.log(res.data);
        this.rentList = res.data;
      }
    },
    // 获取楼宇数据
    async getRentBuildList() {
      let res = await getRentBuildListAPI();
      this.buildList = res.data;
    },
    // 上传合同
    async uploadFile(params) {
      // params是个对象，里面有一个File类型的属性->这个就是我们要上传的文件
      console.log("uploadFile", params.file);

      // 获取文件扩展名
      const fileExtension = params.file.name.split(".").pop().toLowerCase();
      const allowedExtensions = ["doc", "docx", "pdf"];

      // 检查文件类型是否符合要求
      if (!allowedExtensions.includes(fileExtension)) {
        this.$message.error("文件类型不支持，请上传 .doc, .docx 或 .pdf 文件");
        return; // 阻止文件上传
      }

      // 1. 创建 FormData对象
      const formData = new FormData();
      // 2. 使用formData对象的append方法添加参数
      formData.append("file", params.file);
      formData.append("type", "contract");
      // 3. 使用formData对象调用uploadAPI发送请求
      let res = await uploadAPI(formData);
      let { id, url } = res.data;
      this.rentForm.contractId = id;
      this.rentForm.contractUrl = url;
      // 单独校验表单
      this.$refs.addForm.validate("contractId");
    },
    // 提交合同表单
    async submitRentForm() {
      try {
        // 1. 表单合法性验证
        await this.$refs.addForm.validate();

        // 2. 收集接口https://apifox.com/apidoc/shared-04b75e91-2e76-4a88-8774-6e5d65d14b61/api-128582353需要的请求数据
        let data = {
          buildingId: this.rentForm.buildingId,
          enterpriseId: this.rentForm.enterpriseId,
          startTime: this.rentForm.rentTime[0],
          endTime: this.rentForm.rentTime[1],
          contractId: this.rentForm.contractId,
          contractUrl: this.rentForm.contractUrl,
          type: 0, //添加合同
        };
        // console.log("新增合同data：", data);
        // return;

        // 3. 调用接口发送请求
        await createRentAPI(data);
        this.$message.success("新增合同成功");

        // 4. 关闭对话框
        this.rentDialogVisible = false;
      } catch (error) {
        console.log(error);
      }
    },
    // 关闭合同对话框
    closeDialog() {
      this.rentDialogVisible = false;
    },
    // 打开添加合同的对话框
    addRent(row) {
      this.rentForm.enterpriseId = row.id;
      this.rentDialogVisible = true;
    },
    // 分页切换
    pageChange(page) {
      // 更改参数
      this.params.page = page;
      // 重新获取数据渲染
      this.getList();
    },
    // 查询
    doSearch() {
      this.params.page = 1;
      this.getList();
    },
    // 跳转编辑页
    editRent(id) {
      this.$router.push({
        path: "/park/enterprise/add",
        query: {
          id,
        },
      });
    },
    // 删除企业
    delExterprise(id) {
      this.$confirm("确认删除该企业吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        await delExterpriseAPI(id);
        this.getList();
        this.$message({
          type: "success",
          message: "删除成功!",
        });
      });
    },
    // 退租合同
    outRent(rentId) {
      this.$confirm("确认退租吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 1. 调用接口
          await outRentAPI(rentId);
          // 2. 重新拉取列表
          this.getList();
          this.$message({
            type: "success",
            message: "退租成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 删除合同
    async delRent(rentId) {
      this.$confirm("确认删除该合同吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 1. 调用接口
          await delRentAPI(rentId);
          // 2. 重新拉取列表
          this.expandChange(this.currentRow, [this.currentRow]);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 跳转查看页
    viewRent(id) {
      this.$router.push({
        path: "/park/enterprise/view",
        query: {
          id,
        },
      });
    },
  },
  created() {
    // 获取企业列表
    this.getList();

    // 获取楼宇下拉选项的数据
    this.getRentBuildList();
  },
};
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container {
  margin: 10px 0px;
}
.page-container {
  padding: 4px 0px;
  text-align: right;
}
.form-container {
  padding: 0px 80px;
}
</style>